import { NextRequest, NextResponse } from 'next/server';
import UserModel, { UserProfileData } from '@/models/user';
import { authMiddleware, TokenPayload } from '@/utils/auth';

// 获取用户资料以及格式化为面试表单格式
export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 });
    }
    
    const token = authHeader.split(' ')[1];
    
    // 验证token
    const JWT_SECRET = process.env.JWT_SECRET || 'default_secret';
    const decoded = await new Promise((resolve, reject) => {
      require('jsonwebtoken').verify(token, JWT_SECRET, (err: any, decoded: any) => {
        if (err) reject(err);
        else resolve(decoded);
      });
    }) as { id: number };
    
    const userId = decoded.id;
    
    // 获取用户信息
    const user = await UserModel.findById(userId);
    
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }
    
    // 获取额外的用户相关数据
    const workExperiences = await UserModel.getWorkExperiences(userId);
    const educationExperiences = await UserModel.getEducationExperiences(userId);
    const skills = await UserModel.getSkills(userId);
    
    // 计算工作经验总年限
    const calculateTotalYears = (experiences: any[]): number => {
      if (!experiences || experiences.length === 0) return 0;
      
      let totalMonths = 0;
      for (const exp of experiences) {
        const startDate = new Date(exp.start_date);
        const endDate = exp.end_date ? new Date(exp.end_date) : new Date();
        
        const months = (endDate.getFullYear() - startDate.getFullYear()) * 12 + 
                       (endDate.getMonth() - startDate.getMonth());
        totalMonths += months;
      }
      
      return Math.round(totalMonths / 12);
    };
    
    // 获取最高学历
    const getHighestEducation = (eduExperiences: any[]): string => {
      if (!eduExperiences || eduExperiences.length === 0) return '';
      
      const degreeOrder = ['博士', 'PhD', '硕士', 'Master', '本科', 'Bachelor', '专科', '高中'];
      let highestEdu = eduExperiences[0];
      
      for (const edu of eduExperiences) {
        const currentDegreeIndex = degreeOrder.findIndex(d => (edu.degree || '').includes(d));
        const highestDegreeIndex = degreeOrder.findIndex(d => (highestEdu.degree || '').includes(d));
        
        if (currentDegreeIndex !== -1 && (highestDegreeIndex === -1 || currentDegreeIndex < highestDegreeIndex)) {
          highestEdu = edu;
        }
      }
      
      return `${highestEdu.degree || ''}${highestEdu.institution_name ? '，' + highestEdu.institution_name : ''}${highestEdu.field_of_study ? '，' + highestEdu.field_of_study : ''}`;
    };
    
    // 生成自我介绍
    const generateSelfIntro = (user: any, workExps: any[]): string => {
      let intro = `我是${user.username || ''}`;
      
      const totalWorkYears = calculateTotalYears(workExps);
      
      if (workExps && workExps.length > 0) {
        const latestJob = workExps.sort((a, b) => 
          new Date(b.end_date || new Date()).getTime() - new Date(a.end_date || new Date()).getTime()
        )[0];
        
        intro += `，目前/曾经在${latestJob.company_name || ''}担任${latestJob.position || ''}职位`;
      }
      
      if (totalWorkYears > 0) {
        intro += `，有${totalWorkYears}年相关工作经验`;
      }
      
      intro += '。';
      
      // 添加工作经验描述
      if (workExps && workExps.length > 0) {
        intro += '\n\n我的工作经历包括：';
        workExps.slice(0, 3).forEach((exp, index) => {
          intro += `\n${index + 1}. ${exp.company_name || ''}（${exp.position || ''}）：${exp.description ? exp.description.substring(0, 100) + (exp.description.length > 100 ? '...' : '') : '无描述'}`;
        });
      }
      
      // 添加技能信息
      if (skills && skills.length > 0) {
        intro += '\n\n我掌握的技能包括：' + skills.map(s => s.name).join('、');
      }
      
      return intro;
    };
    
    // 返回面试表单需要的格式
    return NextResponse.json({
      name: user.username || '',
      education: getHighestEducation(educationExperiences),
      years: calculateTotalYears(workExperiences).toString(),
      skills: skills.map(s => s.name),
      selfIntro: generateSelfIntro(user, workExperiences)
    });
    
  } catch (error) {
    console.error('获取用户信息时出错:', error);
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// 更新用户资料
export async function PUT(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    // 现在TypeScript知道authResult是TokenPayload类型
    const decoded = authResult as TokenPayload;

    // 获取请求数据
    const body = await request.json();
    const profileData = body as UserProfileData;
    
    // 更新用户资料
    const userId = decoded.id;
    const success = await UserModel.updateProfile(userId, profileData);
    
    if (!success) {
      return NextResponse.json(
        { error: '更新资料失败' },
        { status: 400 }
      );
    }
    
    // 获取更新后的用户信息
    const updatedUser = await UserModel.findById(userId);
    
    if (!updatedUser) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }
    
    // 获取额外的用户相关数据
    const workExperiences = await UserModel.getWorkExperiences(userId);
    const educationExperiences = await UserModel.getEducationExperiences(userId);
    const skills = await UserModel.getSkills(userId);
    
    // 返回更新后的用户资料（不包含密码）
    const { password, ...userInfo } = updatedUser;
    
    return NextResponse.json(
      { 
        message: '更新资料成功',
        user: userInfo,
        workExperiences,
        educationExperiences,
        skills
      },
      { status: 200 }
    );
    
  } catch (error) {
    console.error('更新用户资料错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
} 